package com.drcoffee.drcoffeemall.util;

import com.drcoffee.drcoffeemall.entry.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Component
public class FileUploadDownloadUtil {

    // 文件上传路径
//    @Value("${img_path.initPath_B}")
//    @Value("${nginx_file}")
//    private String initPath;

    // 文件上传
    public static Result uploadFile(MultipartFile file, String filepath, String fileName) throws IOException {
        Map<String, Object> resultMap = new HashMap<>();
        // 检查文件大小
        long maxSize = 2 * 1024 * 1024; // 2MB
        if (file.getSize() > maxSize) {
            // 文件大小不能超过2MB
            return new Result(2, "SUCCESS", "The file size cannot exceed 2MB", null);
        }

        // 获取当前时间戳
        long timestamp = System.currentTimeMillis();

        // 格式化时间戳为字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String formattedTimestamp = sdf.format(new Date(timestamp));

        // 图片文件名
        fileName = "image_" + formattedTimestamp + "_" + fileName;
        int startIndex = filepath.indexOf("PartsMallFile");
        String filePath = filepath.substring(startIndex + "PartsMallFile".length());
        if (!file.isEmpty()) {
            try (BufferedOutputStream out = new BufferedOutputStream(
                    new FileOutputStream((filepath + File.separator + fileName)))) {
                out.write(file.getBytes());
                out.flush();
                return new Result(1, "SUCCESS", "Upload successfully", fileName);

            } catch (FileNotFoundException e) {
                log.error("===================== uploadFile()异常： =====================", e);
                return new Result(-1, "ERROR", "FileNotFoundException: " + e.getMessage(), fileName);

            } catch (IOException e) {
                log.error("===================== uploadFile()异常： =====================", e);
                return new Result(-1, "ERROR", "IOException: " + e.getMessage(), fileName);
            }
        } else {
            return new Result(3, "SUCCESS", "The value of the file argument 'file' is null!", fileName);
        }
    }


    // 获取当前系统路径
    private static String getUploadPath(String strPath) throws IOException {
        File file = new File(strPath);
        File fileParent = file.getParentFile();
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }
        if (!file.exists()) file.mkdirs();
        return file.getAbsolutePath();
    }


    // 下载文件
    public Object downloadFile(String filePath) throws IOException {

        Map<String, Object> resultMap = new HashMap<>();
        File file = new File(filePath);
        if (file.exists()) {
            Path path = file.toPath();
            Resource resource = new UrlResource(path.toUri());
            String contentType = "application/octet-stream";

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(resource);
        } else {
            resultMap.put("result", false);
            resultMap.put("message", "下载失败，文件不存在！");
            return resultMap;
        }
    }

    /**
     * 删除指定文件
     */
    public static boolean deleteFile(String str) {
        String Path = str.replaceAll("/", "\\\\");
        File file = new File(Path);
        if (file.exists()) {
            // 删除指定文件
            Path filePath = Paths.get(Path);
            try {
                Files.delete(filePath);
                System.out.println("文件删除成功！");
                return true;
            } catch (IOException e) {
                System.out.println("文件删除失败：" + e.getMessage());
                return false;
            }
        } else {
            System.out.println("不存在");
            return true;
        }
    }
}
